﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;
using Meeting.Model;
using Newtonsoft.Json;
using System.Configuration;
using Components;

namespace Meeting.Web.ashx
{
    /// <summary>
    /// Meeting 的摘要说明
    /// </summary>
    public class TopicHandler : IHttpHandler
    {
        string methodName = "";
        bool jsonP = false;
        BLL.TopicBLL bll = new BLL.TopicBLL();

        public void ProcessRequest(HttpContext context)
        {
            string header = "{0}";
            try
            {
                String cb = context.Request.Params["callback"]; //  
                //传过来的 callback 参数 假如 Ext.data.JsonP.callback  
                if (cb != null)
                {
                    jsonP = true;
                    context.Response.ContentType = "text/javascript";
                }
                else
                {
                    context.Response.ContentType = "application/x-json;charset=utf-8";
                }

                header = "";
                if (jsonP)
                {
                    header = cb + "({0})";
                }
                else
                {
                    header = "{0}";
                }

                methodName = context.Request.Params["method"];

                switch (methodName.ToLower())
                {
                    case "add":
                        Model.Topic topic = new Topic();
                        string category = context.Request.Params["Category"];
                        topic.Id = new Guid(context.Request.Params["topicId"]);
                        topic.CategoryId = Convert.ToInt32(category.Split('|')[0]);
                        topic.Title = context.Request.Params["Title"];
                        topic.Details = context.Request.Params["Details"];
                        //model.Description = context.Request.Params["Description"];
                        topic.EmployeeId = context.Request.Params["EmployeeId"];
                        topic.EmployeeName = context.Request.Params["EmployeeName"];
                        topic.EmployeeTitle = context.Request.Params["EmployeeTitle"];
                        topic.RoleId = context.Request.Params["RoleId"];
                        topic.Asks = context.Request.Params["Asks"];

                        context.Response.Write(string.Format(header, (topic.Id == Guid.Empty ? bll.Add(topic) : bll.Update(topic))));
                        break;
                    case "updatedesc":
                        Guid topicId = new Guid(context.Request.Params["topicId"]);
                        string desc = context.Request.Params["desc"];
                        string agent = context.Request.Params["agent"];
                        string extNumber = context.Request.Params["ext"];
                        context.Response.Write(string.Format(header, bll.UpdateDescription(topicId, desc, agent, extNumber)));
                        break;
                    //case "edit":
                    //    context.Response.Write(string.Format(header, bll.Update(model)));
                    //    break;
                    case "delete":
                        context.Response.Write(string.Format(header, bll.Delete(Guid.NewGuid())));
                        break;
                    case "getby":
                        topicId = new Guid(context.Request.Params["topicId"]);
                        context.Response.Write(string.Format(header, bll.GetTopicBy(topicId)));
                        break;
                    case "getmy":
                        string empId = context.Request.Params["empId"];
                        context.Response.Write(string.Format(header, bll.GetTopicsBy(empId)));
                        break;
                    case "deltopic":
                        //删除议题，同时删除议题文档，议题地块文本，议题意见（包括图片意见）
                        topicId = new Guid(context.Request.Params["topicId"]);
                        string rootDir = HttpContext.Current.Server.MapPath("~/" + ConfigurationManager.AppSettings["UploadPath"]);
                        //删除之前首先获取各实体对象对应文件的路径
                        //议题文档路径列表
                        List<string> docPaths = bll.GetTopicDocPaths(topicId);
                        //议题地块文档路径列表
                        List<string> platePaths = bll.GetTopicPlatePaths(topicId);
                        //议题审批意见图片路径列表
                        List<string> picPaths = bll.GetApprovePicPaths(topicId);
                        //
                        JsonResponse response = bll.DeleteTopic(topicId);
                        if (response.success)
                        {
                            DirectoryInfo infoExt;
                            string path = "";
                            //删除议题文档
                            if (docPaths != null && docPaths.Count > 0)
                            {
                                docPaths.ForEach(p =>
                                {
                                    //首先判断路径在不在，在的话删除
                                    path = rootDir + "/" + p + "/" + topicId.ToString() + "/";
                                    if (Directory.Exists(path))
                                    {
                                        infoExt = new DirectoryInfo(path);
                                        infoExt.Delete(true);
                                    }
                                });
                            }
                            //删除议题地块
                            if (platePaths != null && platePaths.Count > 0)
                            {
                                platePaths.ForEach(p =>
                                {
                                    //首先判断路径在不在，在的话删除
                                    path = rootDir + "/plate/" + p + "/" + topicId.ToString() + "/";
                                    if (Directory.Exists(path))
                                    {
                                        infoExt = new DirectoryInfo(path);
                                        infoExt.Delete(true);
                                    }
                                });
                            }
                            //删除审批意见图片
                            if (picPaths != null && picPaths.Count > 0)
                            {
                                picPaths.ForEach(p =>
                                {
                                    //首先判断路径在不在，在的话删除
                                    path = rootDir + "/approve/topic/" + p + "/" + topicId.ToString() + "/";
                                    if (Directory.Exists(path))
                                    {
                                        infoExt = new DirectoryInfo(path);
                                        infoExt.Delete(true);
                                    }
                                });
                            }

                            //
                            response = new JsonResponse();
                            response.success = true;
                            response.Message = "";
                            context.Response.Write(string.Format(header, JsonConvert.SerializeObject(response)));
                        }
                        else
                        {
                            context.Response.Write(string.Format(header, JsonConvert.SerializeObject(response)));
                        }
                        break;
                    case "deldoc":
                        Guid docId = new Guid(context.Request.Params["docId"]);
                        //首先从服务器删除文件
                        //文件路径获取
                        Model.TopicDocument doc = bll.GetDocBy(docId);
                        rootDir = HttpContext.Current.Server.MapPath("~/" + ConfigurationManager.AppSettings["UploadPath"]);
                        File.Delete(rootDir + "/" + doc.FilePath);
                        DirectoryInfo info = new DirectoryInfo(rootDir + "/" + doc.ImageDir + "/");
                        info.Delete(true);
                        context.Response.Write(string.Format(header, bll.DeleteDocument(docId)));
                        break;
                    case "delplate":
                        Guid plateId = new Guid(context.Request.Params["plateId"]);
                        //首先从服务器删除文件
                        //文件路径获取
                        Model.TopicPlate plate = bll.GetPlateBy(plateId);
                        rootDir = HttpContext.Current.Server.MapPath("~/" + ConfigurationManager.AppSettings["UploadPath"] + "/plate");
                        File.Delete(rootDir + "/" + plate.Path + "/" + plate.TopicId + "/" + plate.Id.ToString() + "." + plate.Format);
                        context.Response.Write(string.Format(header, bll.DeletePlate(plateId)));
                        break;
                    case "submitmeeting":
                        topicId = new Guid(context.Request.Params["topicId"]);
                        context.Response.Write(string.Format(header, bll.SubmitMeeting(topicId)));
                        break;
                    case "submitcomment":
                        var jSetting = new JsonSerializerSettings();
                        jSetting.NullValueHandling = NullValueHandling.Ignore;
                        Model.TopicApprove approve = JsonConvert.DeserializeObject<Model.TopicApprove>(context.Request["param"], jSetting);
                        context.Response.Write(string.Format(header, bll.SubmitApprove(approve)));
                        break;
                }
            }
            catch (Exception ex)
            {
                JsonResponse response = new JsonResponse();
                response.success = false;
                response.Message = ex.Message;

                context.Response.Write(string.Format(header, JsonConvert.SerializeObject(response)));
            }
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}